import { useState, useEffect } from "react";
import { history } from "umi";
import { connect } from "umi";
import "./ShaoGuangChapterStyles.css";
import Character from "@/components/Character";
import backgroundImage from "@/assets/p1/scenes/shaoguang-background.png";
import dialogImage from "@/assets/p1/dialog_background_red.png";
import protagonistImage from "@/assets/p1/characters/protagonist-right.png";
import TreasureBox from "@/components/TreasureBox";
import AchievementList from "@/components/AchievementList";
import Dialog from "@/components/Dialog";
import front1 from "@/assets/p1/front1-right.png";
import front2 from "@/assets/p1/front2-right.png";
import front3 from "@/assets/p1/front3-right.png";
import back1 from "@/assets/p1/back1.PNG";
import back2 from "@/assets/p1/back2.PNG";
import back3 from "@/assets/p1/back3.PNG";
import left1 from "@/assets/p1/left1.png";
import left2 from "@/assets/p1/left2.png";
import left3 from "@/assets/p1/left3.png";
import right1 from "@/assets/p1/right1.png";
import right2 from "@/assets/p1/right2.png";
import right3 from "@/assets/p1/right3.png";
import landlordImage from "@/assets/p1/characters/landlord.png";
import horseImage from "@/assets/p1/horse-left.png";
import magnifierImage from "@/assets/p1/magnifier.png";
import ironImage from "@/assets/p1/iron.png";
import baiduImage from "@/assets/p1/baidu.png";
import checkImage from "@/assets/p1/checked.png";
import Card from "@/components/Card";

const ShaoGuangChapterScene = ({ dispatch }) => {
	const [footprintsFound, setFootprintsFound] = useState({
		4: false,
	});
	const [showCard1, setShowCard1] = useState(false);
	const [showCard2, setShowCard2] = useState(false);
	const [showCard3, setShowCard3] = useState(false);
	const screenWidth = window.innerWidth; // 1707
	const screenHeight = window.innerHeight; // 791
	// 角色初始位置是 initPositionX 和 initPositionY
	const initPositionX = screenWidth * 0.05;
	const initPositionY = screenHeight * 0.7;
	const [dialog1, setDialog1] = useState(false);
	const [dialog2, setDialog2] = useState(false);
	const [dialog3, setDialog3] = useState(false);
	const [dialog4, setDoalog4] = useState(false);
	const [shaoguangSuccess, setShaoguangSuccess] = useState(false);
	const [balance, setBalance] = useState(false);
	const [characterPosition, setCharacterPosition] = useState({
		x: initPositionX,
		y: initPositionY,
	});
	const [magnifyingGlassPosition, setMagnifyingGlassPosition] = useState({
		x: initPositionX,
		y: initPositionX,
	});
	const [stopMagnifyingGlass, setStopMagnifyingGlass] = useState(false);
	const [showCheck1, setShowCheck1] = useState(false);
	const [showCheck2, setShowCheck2] = useState(false);
	const [showCheck3, setShowCheck3] = useState(false);
	const [showCheck4, setShowCheck4] = useState(false);
	const [horse, setHorse] = useState(false);
	const [finished, setFinished] = useState(false);
	const handlePositionChange = newPosition => {
		setCharacterPosition(newPosition);
	};

	const characterImages = {
		front: [front1, front2, front3, front2],
		left: [left1, left2, left3, left2],
		right: [right1, right2, right3, right2],
		back: [back1, back2, back3, back2]
	};

	// 定义对号图片的点击事件处理函数
	const handleCheckClick = index => {
		if (index === 1) {
			setShowCheck1(true);
		} else if (index === 2) {
			setShowCheck2(true);
		} else if (index === 3) {
			setShowCheck3(true);
		} else if (index === 4) {
			setShowCheck4(true);
		}
	};

	// 更新放大镜位置的状态
	const handleMouseMove = event => {
		if (stopMagnifyingGlass) {
			// 如果已设置停止放大镜移动，则不执行后续操作
			return;
		}
		const { clientX, clientY } = event;
		const magnifierOffsetX = 75;
		const magnifierOffsetY = 75;
		setMagnifyingGlassPosition({
			x: clientX - magnifierOffsetX,
			y: clientY - magnifierOffsetY,
		});
	};
	const dialogues1 = [
		"找到另一个马蹄铁了，应该就是这里了，这里有一个机关塔。",
		"（解机关）",
		"",
	];
	const dialogues2 = ["机关解开，找到了地主家的马。", ""];
	const dialogues3 = [
		"找到马了。",
		"谢谢你啊，是我错怪他们了，作为回报，我赠你一样物品。",
		"",
	];
	const dialogues4 = ["让我看看成就，下一个该去的地方是……"];
	function isFootprintVisible(magnifyingPosition, footprintNumber) {
		const footprintPositions = {
			4: { x: 0.35 * screenWidth, y: 0.58 * screenHeight },
		};
		const footprint = footprintPositions[footprintNumber];
		const range = 50;

		const isVisible =
			magnifyingPosition.x >= footprint.x - range &&
			magnifyingPosition.x <= footprint.x + range &&
			magnifyingPosition.y >= footprint.y - range &&
			magnifyingPosition.y <= footprint.y + range;

		if (footprintNumber === 4 && isVisible && !footprintsFound[4]) {
			setFootprintsFound(prevFound => ({ ...prevFound, 4: true }));
			setTimeout(() => {
				setStopMagnifyingGlass(true);
				handleFootprintFound();
			}, 1000);
		}
		return isVisible;
	}
	// 定义要触发的事件
	function handleFootprintFound() {
		setDialog1(true);
	}

	useEffect(() => {
		if (showCheck1 && showCheck2 && showCheck3 && showCheck4) {
			setTimeout(() => {
				setDialog2(true);
				setShowCard3(false);
			}, 500);
			setTimeout(() => {
				setShowCheck4(false);
			}, 1000);
		}
		// 设置 CSS 变量
		document.documentElement.style.setProperty(
			"--screenWidth",
			`${screenWidth}px`
		);
		document.documentElement.style.setProperty(
			"--screenHeight",
			`${screenHeight}px`
		);
		if (
			Math.sqrt(
				Math.pow(characterPosition.x - 0.6 * screenWidth, 2) +
					Math.pow(characterPosition.y - screenHeight * 0.6, 2)
			) <= 150 &&
			!dialog1 &&
			!showCard1 &&
			!showCard2 &&
			!showCard3 &&
			!dialog2 &&
			!dialog3 &&
			!dialog4 &&
			!balance &&
			!horse
		) {
			setShowCard1(true);
		}
	}, [
		characterPosition.x,
		characterPosition.y,
		showCheck1,
		showCheck2,
		showCheck3,
		showCheck4,
		shaoguangSuccess,
		balance,
		finished,
	]);
	return (
		<div
			className="backgroundImage"
			style={{ backgroundImage: `url(${backgroundImage})` }}
			onMouseMove={handleMouseMove} // 添加鼠标移动事件处理函数
		>
			<TreasureBox />
			<AchievementList
				achievementId={5}
				handleClick={
					finished
						? () => {
								history.push("/p2/sumi");
							}
						: () => {}
				}
			/>
			{shaoguangSuccess && (
				<Card
					cardId={4}
					visible={true}
					onClick={() => {
						setDialog3(true);
						setShaoguangSuccess(false);
						setHorse(true);
					}}
				>
					<p>获得成就</p>
					<p>少广</p>
				</Card>
			)}
			{balance && (
				<Card
					visible={true}
					onClick={() => {
						setBalance(false);
						setDoalog4(true);
					}}
				>
					<p>获得物品</p>
					<p>天平</p>
				</Card>
			)}

			<Character
				characterImage={protagonistImage}
				characterImages={characterImages}
				canMove={true}
				initPositionX={initPositionX}
				initPositionY={initPositionY}
				onPositionChange={handlePositionChange}
				ifProtagonist="true"
			/>
			{horse && (
				<Character
					characterImage={landlordImage}
					initPositionX={0.85 * screenWidth}
					initPositionY={0.5 * screenHeight}
				/>
			)}
			{horse && (
				<img
					src={horseImage}
					style={{ position: "absolute", left: "75vw", top: "50vh" }}
				/>
			)}

			{dialog1 && (
				<Dialog
					dialogues={dialogues1}
					backgroundImage={dialogImage}
					triggerIndexEvents={[2]}
					eventHandlers={[
						() => {
							setDialog1(false);
						},
					]}
					dialogueImages={[{ leftImage: protagonistImage }]}
				/>
			)}
			{dialog2 && (
				<Dialog
					dialogues={dialogues2}
					backgroundImage={dialogImage}
					triggerIndexEvents={[1]}
					eventHandlers={[
						() => {
							setShaoguangSuccess(true);
							setDialog2(false);
							setHorse(true);
						},
					]}
					dialogueImages={[{ leftImage: protagonistImage }]}
				/>
			)}
			{dialog3 && (
				<Dialog
					dialogues={dialogues3}
					backgroundImage={dialogImage}
					triggerIndexEvents={[1, 2]}
					eventHandlers={[
						() => {
							dispatch({
								type: "treasureBox/showItem",
								payload: 4,
							});
						},
						() => {
							setHorse(false);
							setBalance(true);
							setDialog3(false);
						},
					]}
					dialogueImages={[
						{ leftImage: protagonistImage },
						{ rightImage: landlordImage },
					]}
				/>
			)}
			{dialog4 && (
				<Dialog
					dialogues={dialogues4}
					backgroundImage={dialogImage}
					triggerIndexEvents={[0]}
					eventHandlers={[
						() => {
							setBalance(false);
							setFinished(true);
						},
					]}
					dialogueImages={[{ leftImage: protagonistImage }]}
				/>
			)}
			<img
				className={`footprints num4 ${isFootprintVisible(magnifyingGlassPosition, 4) ? "visible" : ""}`}
				src={ironImage}
				alt="马蹄铁"
			/>

			<img
				src={magnifierImage}
				className={"magnifierImage"}
				style={{
					left: `${magnifyingGlassPosition.x}px`,
					top: `${magnifyingGlassPosition.y}px`,
				}}
			/>
			{showCard1 && (
				<div
					onClick={() => {
						setShowCard1(false);
						setShowCard2(true);
					}}
					className="card1"
				>
					<div>点击算筹，展开用法以及机关详情</div>
				</div>
			)}
			{showCard2 && (
				<div
					onClick={() => {
						setShowCard2(false);
						setShowCard3(true);
					}}
					className="card2"
				>
					<div className="intro">
						算筹，是在珠算发明以前中国独创并且是最有效的计算工具，中国古代数学的发达与持续发展是受惠于筹的。
					</div>
					<div>算筹数字表示法</div>
					<img src={baiduImage} />
				</div>
			)}
			{showCard3 && (
				<div className="card3_4">
					<div className="card3"></div>
					<div className="card4">
						<img
							id="checkImage1"
							src={checkImage}
							className={showCheck1 ? "visible" : ""}
							onClick={() => handleCheckClick(1)}
						/>
						<img
							src={checkImage}
							className={showCheck2 ? "visible" : ""}
							onClick={() => handleCheckClick(2)}
						/>
						<img
							src={checkImage}
							className={showCheck3 ? "visible" : ""}
							onClick={() => handleCheckClick(3)}
						/>
						<img
							src={checkImage}
							className={showCheck4 ? "visible" : ""}
							onClick={() => handleCheckClick(4)}
						/>
					</div>
				</div>
			)}
		</div>
	);
};

export default connect(() => {})(ShaoGuangChapterScene);
